package com.ruoyi.common.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.system.SystemUtil;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.utils.sign.Base64;
import lombok.Data;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Sdk2SmsSend extends BaseSmsSend {

    private static final String sendUrl = "http://1.85.55.225:8888/expert-sms3/sms/submit";

    private static final String queryUrl = "http://1.85.55.225:8888/expert-sms3/sms/report";
    private static final String userAccount = "zjglxt";
    private static final String password = "D0UYRCVs.JE";
    private static final String ecname = "陕西省应急管理厅";
    private static final String sign = "pxKGAdISL";
    private static final String addSerial = "";


    private static Log log = LogFactory.getLog(Sdk2SmsSend.class);
    @Data
    public static class SendResponse {
        private String rspcod;
        private Boolean success;
        private String msgGroup;
        // 是否发送成功，这个不是最终状态。最终状态需要通过订单查询接口查询。
        public boolean isSuccess() {
            return success != null && success;
        }
    }
    @Data
    public static class QuerySendResponse {
        private String errorCode;
        private String mobile;
        private String msgGroup;
        private String receiveDate; //2025 06 21 22 34 00
        private String receiveDateFormat; //2025 06 21 22 34 00
        private String reportStatus; //"CM:0000"
        private String submitDate; //20250621223400
        private String submitDateFormat; //20250621223400
        // 是否发送成功，这个不是最终状态。最终状态需要通过订单查询接口查询。
        public boolean isSuccess() {
            return "DELIVRD".equals(errorCode);
        }

        public String getReceiveDateFormat() {
            if (StrUtil.isBlank(receiveDateFormat)) {
                receiveDateFormat = DateUtil.format(DateUtil.parse(receiveDate), "yyyy-MM-dd HH:mm:ss");
            }
            return receiveDateFormat;
        }

        public String getSubmitDateFormat() {
            if (StrUtil.isBlank(submitDateFormat)) {
                submitDateFormat = DateUtil.format(DateUtil.parse(submitDate), "yyyy-MM-dd HH:mm:ss");
            }
            return submitDateFormat;
        }
    }

    //[{"errorCode":"DELIVRD","mobile":"18392447939","msgGroup":"0621223418000500928596"
    // ,"receiveDate":"20250621223400","reportStatus":"CM:0000","submitDate":"20250621223400"}]

    /**
     * ecName	String	企业名称。
     * apId	String	接口账号用户名。
     * mobiles	String	收信手机号码。英文逗号分隔，每批次限5000个号码，例：“13800138000,13800138001,13800138002”。
     * content	String	短信内容。
     * sign	String	签名编码。在云MAS平台『管理』→『接口管理』→『短信接入用户管理』获取。
     * addSerial	String	扩展码。依据申请开户的服务代码匹配类型而定，如为精确匹配，此项填写空字符串（""）；如为模糊匹配，此项可填写空字符串或自定义的扩展码，注：服务代码加扩展码总长度不能超过20位。
     * mac	String	参数校验序列，生成方法：将ecName、apId、secretKey、mobiles、content、sign、addSerial按序拼接（无间隔符），通过MD5（32位小写）计算得出值。
     */
    public SmsSendResponse send(String mobiles, String content) throws UnsupportedEncodingException {
        /*if(SystemUtil.getOsInfo().isWindows()){
            SmsSendResponse response = new SmsSendResponse();
            response.setBatchNo(IdUtil.simpleUUID());
            response.setMsg("成功");
            response.setSuccess(true);
            return response;
        }*/
        content = "《专家管理系统》" + content;
        Map<String, Object> map = new HashMap(6);
        map.put("ecName", ecname);
        map.put("apId", userAccount);
        map.put("mobiles", mobiles);
        map.put("content",content);
        map.put("sign", sign);
        map.put("addSerial", addSerial);
        log.info("ecname = "  + ecname);
        log.info("userAccount = "  + userAccount);
        log.info("password = "  + password);
        //map.put("mac", SecureUtil.md5(userAccount + password + ecname + content + sign + "123"));
        //ecName、apId、secretKey、mobiles、content、sign、addSerial
        map.put("mac", SecureUtil.md5(ecname + userAccount + password +mobiles+  content + sign + addSerial));
        String paramStr = Base64.encode(JSON.toJSONString(map).getBytes("utf-8"));


        String body = HttpUtil.post(sendUrl, paramStr , 60000);
        log.info("meiya send api, send params, url:"+sendUrl+", map:"+JSONUtil.toJsonStr(map));
        log.info("meiya send api, get body:" +  body); //{"msgGroup":"0621223418000500928596","rspcod":"success","success":true}
        log.info(paramStr);

        if (StrUtil.isBlank(body)) {
            return new SmsSendResponse();
        } else {
            SendResponse sendResponse = JSON.parseObject(body, Sdk2SmsSend.SendResponse.class);
            SmsSendResponse response = new SmsSendResponse();
            response.setBatchNo(sendResponse.getMsgGroup());
            response.setMsg(sendResponse.getRspcod());
            response.setSuccess(sendResponse.isSuccess());
            return response;
        }
    }
    public List<SmsQueryResponseOrder> query(String msgGroup) {
        Map<String, Object> map = new HashMap(6);
        map.put("ecName", ecname);
        map.put("apId", userAccount);
        map.put("secretKey", password);
        map.put("msgGroup", msgGroup);
        String body = HttpUtil.post(queryUrl, Base64.encode(JSON.toJSONString(map).getBytes()) , 60000);
        log.info("meiya send api, send params, url:"+queryUrl+", map:"+JSONUtil.toJsonStr(map));
        log.info("meiya send api, get body:" +  body);
        if (StrUtil.isBlank(body) || !body.startsWith("[")) {
            return new ArrayList<>();
        } else {
            List<QuerySendResponse> querySendResponses = JSON.parseArray(body, QuerySendResponse.class);

            List<SmsQueryResponseOrder> responseOrderList = new ArrayList<>();
            for (int i = 0; i < querySendResponses.size(); i++) {
                QuerySendResponse querySendResponse = querySendResponses.get(i);
                SmsQueryResponseOrder responseOrder = new SmsQueryResponseOrder();
                responseOrder.setMobile(querySendResponse.getMobile());
                responseOrder.setError(!querySendResponse.isSuccess());
                responseOrder.setSuccess(querySendResponse.isSuccess());
                responseOrder.setOrderId(querySendResponse.getMsgGroup());
                responseOrder.setMsg(querySendResponse.getErrorCode());
                responseOrder.setSendTime(querySendResponse.getReceiveDateFormat());
                responseOrder.setSubmitTime(querySendResponse.getSubmitDateFormat());
                responseOrder.setErrorCode(querySendResponse.getErrorCode());
                responseOrderList.add(responseOrder);
            }
            return responseOrderList;
        }
        //[{"errorCode":"DELIVRD","mobile":"18392447939","msgGroup":"0621223418000500928596"
        // ,"receiveDate":"20250621223400","reportStatus":"CM:0000","submitDate":"20250621223400"}]
    }
    public static void main(String[] args) throws UnsupportedEncodingException {
        //SmsSendResponse sendResponse = new Sdk2SmsSend().send("15175565261", "您的验证码是:1235");
        //log.info("meiya send api, sendResponse:" + sendResponse);
        new Sdk2SmsSend().query("0918144635000500112276");

    }

}
